import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Login from '../views/login/index.vue'
import { userInfoApi } from '@/http/api'
import { useUserStore } from '@/store/user'
import { ElMessage } from "element-plus"
const routes: RouteRecordRaw[] = [
    {
        path: "/login",
        component: Login
    },
    {
        path: '/',
        redirect: "/index"
    },
    {
        path: "/",
        component: () => import("../views/home/index.vue"),
        children: [
            {
                path: "index",
                component: () => import("../views/index/index.vue"),
            },
        ],
    },
]
const router = createRouter({
    routes,
    history: createWebHashHistory()
})

router.beforeEach((to, from, next) => {
    const store = useUserStore();
    let token = localStorage.getItem("token");
    // 因为每个页面都需要进行 权限的验证，所以在这里面判断 菜单数据有了没有，如果没有，我们需要发请求，来动态获取菜单数据
    if (store.menus.length === 0 && token) {
        // 我们会把请求成功后的菜单数据放在pinia里面
        userInfoApi().then((res) => {
            if (res.code === 200) {
                // 把数据存到pinia
                // pinia里面可以直接修改数据
                store.menus = res.data.menus;
                store.username = res.data.username
                store.routers.forEach(p => {
                    router.addRoute({
                        path: "/" + p.name,
                        name: p.name,
                        component: () => import("../views/home/index.vue"),
                        children: p.children.map(item => ({
                            path: item.name,
                            name: item.name,
                            component: () => import(`../views/${p.name}/${item.name}.vue`),
                        }))
                    })
                })
                next(to.fullPath)
            }
        });
    } else
        // 判断有无token，如果没有，而且访问的不是login 就跳转回login
        if (!token && to.path !== '/login') {
            ElMessage.error("请先登录")
            next('/login')
        }
        //如果已登录，不能直接通过url回到登录页 
        else if (token && store.menus.length !== 0 && to.path === "/login") {
            ElMessage.warning("请先退出登录再重新登录")
            // 跳转回原来的页面
            next(from.fullPath)
        }
        else {
            next();
        }

});
export default router